package com.np.service_demo1.services;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import java.util.Random;

public class BindService extends Service {

    private static final String TAG = BindService.class.getSimpleName();
    private XBinder mBinder = new XBinder();

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate --> Thread: " + Thread.currentThread().getName());
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand --> startId:" + startId + "; Thread:" + Thread.currentThread().getName());
        return START_NOT_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind --> Thread: " + Thread.currentThread().getName());
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind --> from: " + intent.getStringExtra("from"));
        return false;
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy --> Thread: " + Thread.currentThread().getName());
        super.onDestroy();
    }

    //getRandomNumber是Service暴露出去供client调用的公共方法
    public int getRandomNumber() {
        return new Random().nextInt();
    }

    public class XBinder extends Binder {
        public BindService getServices() {
            return BindService.this;
        }
    }
}
